package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.HttpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.view.R;

public class HttpTestWidgetProxy extends GeneralTestWidget {
	private ScrollView sView;
	private LinearLayout httpTestDetail;
	private HttpTestManager httpTestManager;
	private LinearLayout chartLayout;
	private Activity ctx;
	private Task task;
	private HttpTask httpTask;
	private Button btnBack;
	private Handler httpTestHandler;
	private int taskSize;
	private int currentTaskNum;
	private boolean taskProcessing;
	private List<double[]> tempYdatas;
	private int testedTimes;

	public HttpTestWidgetProxy(Activity context) {
		super(context);
		inflate(context, R.layout.http_test_widget_proxy, this);
		this.ctx = context;
		sView = (ScrollView) this.findViewById(R.id.http_test_proxy_ScrView);
		btnBack = (Button) this.findViewById(R.id.http_test_proxy_btnBack);
		httpTestDetail = (LinearLayout) this
				.findViewById(R.id.http_test_proxy_detail);
		chartLayout = (LinearLayout) this
				.findViewById(R.id.httpTestProxyChartLayout);

		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backToTask(ctx);
			}
		});

		// 定义HTTP 测试句柄，获得每次测试结果
		httpTestHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.DONE:
					finishPerTask();
					break;
				case MessageWhat.DO_NEXT_TEST:
					doFtpTest();
					break;
				default:
					updateHttpTestResult(msg.what);
				}
			}
		};
		httpTestManager = new HttpTestManager(ctx);
		httpTestManager.setHandler(httpTestHandler);
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
		startHttpTest();
	}

	private void doFtpTest() {
		FtpTestProxyWidget fp = new FtpTestProxyWidget(ctx);
		ctx.setContentView(fp);
	}

	private void doNextTest() {
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				httpTestManager.sendMsg(MessageWhat.DO_NEXT_TEST);
			}
		};
		Timer t = new Timer();
		t.schedule(timerTask, TASK_PERFORM_INTERVAL);
		this.showMessage(ctx, "HTTP测试已完成，10秒后进入下一项测试");
	}

	public void startHttpTest() {
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		final List<HttpTask> l = task.httpTasks;
		taskSize = l.size();
		showProgressDialog(ctx, "正在进行HTTP测试...", task.testCount*taskSize);
		tempYdatas = new ArrayList<double[]>(taskSize);
		new Thread() {
			public void run() {
				while (currentTaskNum < taskSize) {
					if (!taskProcessing) {
						httpTask = l.get(currentTaskNum);
						currentTaskNum++;
						taskProcessing = true;
						httpTestManager.startHttpTest(httpTask.address,
								task.testCount);
					}
				}
				if (currentTaskNum == taskSize) {
					httpTestManager.sendMsg(MessageWhat.TASK_FINISHED);
				}
			}
		}.start();
	}

	private void finishPerTask() {
		DecimalFormat df = new DecimalFormat("#0.000");
		// int times = httpTestManager.getXdata().length;
		int times = task.testCount;
		tempYdatas.add(httpTestManager.getYdata());
		long size = httpTestManager.getPageLength();
		float delay = (float) httpTestManager.totalDelayTime / times;
		float speed = (delay == 0) ? 0 : ((float) size / 1024)
				/ ((float) delay / 1000);
		// Log.e("", String.valueOf(size));
		httpTask.delay = df.format((float) delay / 1000);
		httpTask.speed = df.format(speed);
		httpTask.failedTimes = httpTestManager.failedTimes;
		task.httpTasks.set(currentTaskNum - 1, httpTask);
		// Log.e("Test", "task:" + task.httpTasks.get(0).speed);

		StringBuffer result = new StringBuffer();
		result.append("测试次数=").append(times);
		result.append(",平均时延=").append(httpTask.delay);
		result.append(" s");
		result.append(",平均下载速率=").append(httpTask.speed).append(" kb/s");
		TextView tv = new TextView(ctx);
		tv.setTextSize(13);
		tv.setTextColor(Color.CYAN);
		tv.setText(result);
		httpTestDetail.addView(tv);
		setScrollViewDown(sView);
		taskProcessing = false;
		httpTestManager.processing = false;
		httpTestManager.currentTime = 0;
		httpTestManager.delayTime = 0;
		httpTestManager.totalDelayTime = 0;
		if (currentTaskNum == taskSize) {
			int length = taskSize * task.testCount;
			double[] ydatas = new double[length];
			double[] xdatas = new double[length];
			for (int i = 0; i < length; i++) {
				xdatas[i] = i + 1;
			}

			int isize = tempYdatas.size();
			for (int i = 0; i < isize; i++) {
				double[] tYdata = tempYdatas.get(i);
				int len = tYdata.length;
				System.arraycopy(tYdata, 0, ydatas, i * len, len);
			}
			ChartManager cm = new ChartManager(ctx, length, 20);
			String chartTitle = "HTTP页面访问测试";
			String[] lineTitles = new String[] { "页面访问时延" };
			List<double[]> x = new ArrayList<double[]>(1);
			List<double[]> y = new ArrayList<double[]>(1);
			// x.add(httpTestManager.getXdata());
			// y.add(httpTestManager.getYdata());
			x.add(xdatas);
			y.add(ydatas);
			int[] colors = new int[] { Color.GREEN };
			View lineChart = cm.createLineChart(colors, chartTitle, lineTitles,
					x, y);
			chartLayout.addView(lineChart);
			// 更新Task的HTTP task数据
			ctx.getIntent().putExtra(TAG_REFER_TASK, task);
			dismissProgressDialog();
			doNextTest();
		}
	}

	private void updateHttpTestResult(int what) {
		testedTimes++;
		this.setDialogProgress(testedTimes);
		DecimalFormat df = new DecimalFormat("#0.000");
		StringBuffer sb = null;
		httpTestManager.processing = false;
		int currentTime = httpTestManager.getCurrentTime();
		if (what == MessageWhat.HTTP_PAGELOAD_SUCCESS) {
			long delayTime = httpTestManager.getDelayTime();
			sb = new StringBuffer();
			sb.append("第").append(currentTime).append("次 ")
					.append(httpTestManager.getAddress()).append(" 页面访问时延：")
					.append(df.format((float) delayTime / 1000)).append(" s");
		} else if (what == MessageWhat.HTTP_PAGELOAD_FAILED) {
			httpTestManager.failedTimes ++;
			sb = new StringBuffer();
			sb.append("第").append(currentTime).append("次 ")
					.append(httpTestManager.getAddress()).append(" 页面访问失败.");
		}
		TextView text = new TextView(ctx);
		text.setText(sb);
		text.setTextSize(12);
		httpTestDetail.addView(text);
		setScrollViewDown(sView);
	}
}
